<template>
  <div class="app">
    <div :class="smallSize?'search-bar':'search-bar-small'">
      <el-form :model="searchData" label-width="68px">
        <el-row :gutter="5">
          <el-col :span="4" :xs="12" :sm="12" :md="4">
            <el-form-item label="公司" style="margin-bottom: 5px;">
              <el-select v-model="searchData.cmhkId" class="select-item"
                size="medium"
                filterable
                clearable
                remote
                reserve-keyword
                :remote-method="remoteMethod"
                @change="selectCompany"
                placeholder="请输入字段搜索">
                <el-option
                  v-for="item in cmhkIdOption"
                  :key="item.code"
                  :label="item.companyChiName"
                  :value="item.cmhkId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" :xs="12" :sm="12" :md="5">
            <el-form-item label="档案类型" style="margin-bottom: 5px;">
              <el-select v-model="searchData.archivesType" size="medium" class="select-item" clearable>
                <el-option
                  v-for="item in archivesTypeOptions"
                  :key="item.index"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" :xs="12" :sm="10" :md="5">
            <el-form-item label="档案名称" style="margin-bottom: 5px;">
              <el-input v-model="searchData.archivesName" size="medium" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5" :xs="12" :sm="9" :md="5">
            <el-form-item label="档案日期" style="margin-bottom: 5px;">
              <el-date-picker
                v-model="searchData.date"
                type="daterange"
                clearable
                range-separator="-"
                start-placeholder="开始日期"
                size="medium"
                end-placeholder="结束日期"
                @change="selectDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                class="select-item" />
            </el-form-item>
          </el-col>
          <el-col :span="5" :xs="12" :sm="5" :md="5">
            <div style="margin-top: 3px">
              <el-button icon="el-icon-search" type="primary" size="small" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" size="small" @click="handleClear">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div ref="ref" :class="canUsed?'table-box':'table-box2'">
      <div class="but-nav">
        <el-button icon="el-icon-plus" v-show="canUsed" type="primary" size="small" @click="handleAddDoc">新增</el-button>
      </div>
      <tableComponent class="table" :height="height" :data="tableData || []" :columns="archivesManageColumns" @change="onTableChange" :table-option="tableOption" :page-option="searchData.page" :total="total">
        <template slot-scope="scope">
          <el-button type="text" @click="seeItem(scope.scope.row)">查看</el-button>
          <el-button v-show="canUsed" type="text" @click="editItem(scope.scope.row)">修改</el-button>
        </template>
      </tableComponent>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisibleEdit" width="80%" top="5vh">
      <div ref="dialogBox2">
        <el-form ref="form" :model="addForm" label-width="90px" :rules="rules" label-position="left" style="padding: 0 20px;" :disabled="ifDisabled">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="档案类型" prop="archivesType" style="margin-bottom: 12px;margin-left: -9px">
                <el-select v-model="addForm.archivesType" size="small" class="select-item" style="width: calc(100% - 9px);margin-left: 9px">
                  <el-option
                    v-for="item in archivesTypeOptions"
                    :key="item.index"
                    :label="item.value"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="文件上传" prop="file" style="margin-bottom: 12px;">
                <el-upload
                  ref="file"
                  action=""
                  :file-list="fileList"
                  :on-change="changeFiles"
                  :show-file-list="showFileList"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="档案名称" prop="archivesName" style="margin-bottom: 12px;margin-left: -9px">
                <el-input v-model="addForm.archivesName" size="small" style="width: calc(100% - 9px);margin-left: 9px"></el-input>
              </el-form-item>
              <el-form-item label="档案日期" prop="archivesDate" style="margin-bottom: 12px;margin-left: -9px">
                <el-date-picker class="select-item" type="date" placeholder="选择日期" v-model="addForm.archivesDate" size="small" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: calc(100% - 9px);margin-left: 9px"></el-date-picker>
              </el-form-item>
              <el-form-item label="档案说明" prop="explanation" style="margin-bottom: 12px;">
                <el-input type="textarea" v-model="addForm.explanation"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <tableComponent
          class="table-file"
          :height="heightDialog2"
          :data="dialogTableData || []"
          :columns="fileTableEditColumns"
          :table-option="tableOption"
          :total="total"
        >
        <template scope="scope">
          <el-button v-show="ifEdit" @click="editFiles(scope.scope.row)" type="text" size="mini">编辑</el-button>
          <el-button @click="downLoadFile(scope.scope.row)" type="text" size="mini">下载</el-button>
          <el-button v-show="ifEdit" @click="delRow(scope.scope.row)" type="text" size="mini">删除</el-button>
        </template>
        </tableComponent>
      </div>
      <span slot="footer">
        <el-button @click="handleCancleEdit">取 消</el-button>
        <el-button type="primary" @click="handleSubmitEdit('form')" v-if="!ifDisabled">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="新增" :visible.sync="dialogVisibleAdd" width="80%" top="5vh">
      <div ref="dialogBox">
        <el-form ref="form" :model="addForm" label-width="90px" :rules="rules" label-position="left" style="padding: 0 20px;">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="档案类型" prop="archivesType" style="margin-bottom: 12px;margin-left: -9px">
                <el-select v-model="addForm.archivesType" size="small" class="select-item" style="width: calc(100% - 9px); margin-left: 9px">
                  <el-option
                    v-for="item in archivesTypeOptions"
                    :key="item.index"
                    :label="item.value"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="文件上传" prop="file" style="margin-bottom: 12px;">
                <el-upload
                  ref="file"
                  action=""
                  :file-list="fileListAdd"
                  :on-change="changeFilesAdd"
                  :on-remove="removeFile"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="档案名称" prop="archivesName" style="margin-bottom: 12px;margin-left: -9px">
                <el-input v-model="addForm.archivesName" size="small" style="width: calc(100% - 9px); margin-left: 9px"></el-input>
              </el-form-item>
              <el-form-item label="档案日期" prop="archivesDate" style="margin-bottom: 12px;margin-left: -9px">
                <el-date-picker class="select-item" type="date" placeholder="选择日期" v-model="addForm.archivesDate" size="small" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: calc(100% - 9px); margin-left: 9px"></el-date-picker>
              </el-form-item>
              <el-form-item label="档案说明" prop="explanation" style="margin-bottom: 12px;">
                <el-input type="textarea" v-model="addForm.explanation"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <tableComponent
          class="table-file"
          :height="heightDialog"
          :data="dialogTableDataAdd || []"
          :columns="fileTableColumns"
          :table-option="tableOptionAdd"
          :total="total"
          :ifNoEditColumns="noEditColumnsArchives"
          @selectChange="handleSelect"
        >
        </tableComponent>
      </div>
      <span slot="footer">
        <el-button @click="handleCancleAdd">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('form')" v-if="!ifDisabled">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改文件信息" :visible.sync="dialogFiles" width="50%" top="5vh">
      <el-form ref="file" :model="fileForm" label-position="left" label-width="80px" :rules="fileRules">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="文件名" prop="name">
              <el-input v-model="fileForm.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="上传时间" prop="fileUploadDate">
              <el-input v-model="fileForm.fileUploadDate" disabled></el-input>
            </el-form-item>
            <el-form-item label="文件类型" prop="documentType">
              <el-select v-model="fileForm.documentType" @change="changeType" clearable class="select-item">
                <el-option
                  v-for="item in documentTypeOption"
                  :key="item.code"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小" prop="size">
              <el-input v-model="fileForm.size" disabled></el-input>
            </el-form-item>
            <el-form-item label="上传人" prop="fileUpleader">
              <el-input v-model="fileForm.fileUpleader" disabled></el-input>
            </el-form-item>
            <el-form-item label="文件细类" prop="documentCategory">
              <el-select v-model="fileForm.documentCategory" clearable class="select-item">
                <el-option
                  v-for="item in documentCategoryOption"
                  :key="item.code"
                  :label="item.value"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="文件说明" prop="remark">
          <el-input type="textarea" v-model="addForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="handleCancleFile">取 消</el-button>
        <el-button type="primary" @click="handleSubmitFile('file')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableComponent from '@/components/Table/table'
import { archivesManageColumns, fileTableEditColumns } from './index.js'
import {
  taskArchives,
  queryCompanyInfoListNoPage,
  queryArchivesTypes,
  addArchives,
  getFileType,
  getDetailFileType,
  queryOneArchives,
  updateArchives,
  deleteArchivesFile,
  autoUploadFile,
  queryFileInfor,
  editFileInfor
} from '@/api/modules/archivesManage.js'
export default {
  components: {
    tableComponent
  },
  watch: {
    screenWidth: {
      handler(val) {
        this.windowWidth(val)
      },
      immediate: true
    }
  },
  data() {
    return {
      searchData: {
        cmhkId: '',
        archivesName: '',
        page: {
          pageNum: 1,
          pageSize: 10
        }
      },
      archivesTypeOptions: [],
      cmhkIdOption: [],
      height: null,
      tableData: [],
      archivesManageColumns,
      tableOption: {
        isShowOperate: true,
        operateWidth: '100px',
        NoInlineEdit: true
      },
      tableOptionAdd: {
        isShowOperate: false,
        NoInlineEdit: true
      },
      total: 0,
      // dialog=========================
      title: '',
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      addForm: {
        cmhkId: '',
        archivesType: '',
        archivesName: '',
        archivesDate: '',
        explanation: ''
      },
      rules: {
        archivesType: [{required: true, message: '请先选择档案类型', trigger: 'change'}],
        archivesName: [{required: true, message: '请输入档案名称', trigger: 'change'}],
        archivesDate: [{required: true, message: '请先选择档案日期', trigger: 'change'}],
      },
      fileList: [],
      fileListAdd: [],
      heightDialog: 300,
      heightDialog2: 300,
      dialogTableData: [],
      dialogTableDataAdd: [],
      fileTableColumns: [
        {
          name: '文件类型',
          value: 'documentType',
          align: 'center',
          isSelect: true,
          selectData: []
        },{
          name: '文件细类',
          value: 'documentCategory',
          align: 'center',
          isSelect: true,
          selectData: []
        },{
          name: '文件说明',
          value: 'remark',
          align: 'center'
        }
      ],
      noEditColumnsArchives: [
        {
          name: '文件名',
          value: 'name',
          align: 'center'
        },{
          name: '文件大小',
          value: 'size',
          align: 'center'
        },{
          name: '上传时间',
          value: 'fileUploadDate',
          align: 'center'
        },{
          name: '上传人',
          value: 'fileUpleader',
          align: 'center'
        }
      ],
      fileTableEditColumns,
      // 文件配置dialog================
      ifDisabled: false,
      saveId: {
        archivesId: '',
        cmhkId: ''
      },
      showFileList: false,
      ifEdit: true,
      // 修改文件信息dialog=============
      dialogFiles: false,
      fileForm: {
        name: '',
        size: '',
        fileUploadDate: '',
        fileUpleader: '',
        documentType: '',
        documentCategory: '',
        remark: ''
      },
      documentTypeOption: [],
      documentCategoryOption: [],
      fileRules: {
        documentType: [{required: true, message: '请选择文件类型', trigger: 'change'}],
      },
      canUsed: true, // 判断权限
      screenWidth: document.documentElement.clientWidth,
      smallSize: true
    }
  },
  mounted() {
    const key = this.$store.state.key.resourceCode
    if (key === '0') {
      this.canUsed = false
    } else {
      this.canUsed = true
    }
    this.$nextTick(() => {
      this.height = this.$refs.ref.offsetHeight
    })
    const that = this
    window.onresize = () => {
      that.height = that.$refs.ref.offsetHeight
      const val = document.documentElement.clientWidth
      that.screenWidth = val
    }
    // 查询档案类型
    queryArchivesTypes().then(res => {
      if (res.data.code === '0') {
        this.archivesTypeOptions = res.data.body
      }
    })
  },
  destroyed(){
    window.onresize = null
  },
  methods: {
    // 远程查询公司
    remoteMethod(query) {
      const data = {
        companyName: query
      }
      queryCompanyInfoListNoPage(data).then(res => {
        if (res.data.code === '0') {
          this.cmhkIdOption = res.data.body
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    initData(params) {
      taskArchives(params).then(res => {
        if (res.data.code === '0') {
          this.tableData = res.data.body.list
          this.total = res.data.body.total
        }
      })
    },
    // 分页操作
    onTableChange(val) {
      this.searchData.page = val
      this.initData(this.searchData)
    },
    // 查看
    seeItem(row) {
      this.dialogVisibleEdit = true
      this.ifDisabled = true
      this.ifEdit = false
      this.title = '查看'
      const data = {
        cmhkId: row.cmhkId,
        archivesId: row.archivesId
      }
      queryOneArchives(data).then(res => {
        if (res.data.code === '0') {
          this.addForm = res.data.body
          this.fileList = res.data.body.list
          this.dialogTableData = res.data.body.list
        }
      })
    },
    // 编辑
    editItem(row) {
      console.log(row)
      this.dialogVisibleEdit = true
      this.ifDisabled = false
      this.ifEdit = true
      this.title = '修改'
      this.saveId.archivesId = row.archivesId
      this.saveId.cmhkId = row.cmhkId
      queryOneArchives(this.saveId).then(res => {
        if (res.data.code === '0') {
          this.addForm = res.data.body
          this.fileList = res.data.body.list
          this.dialogTableData = res.data.body.list
        }
      })
      // getFileType().then(res =>{
      //   if (res.data.code === '0') {
      //     this.fileTableColumns[0].selectData = res.data.body
      //   }
      // })
      // const data = {
      //   parentId: row.archivesType
      // }
      // getDetailFileType(data).then(res => {
      //   if (res.data.code === '0') {
      //     // this.fileTableColumns[1].selectData = []
      //     // this.fileTableColumns[1].selectData = res.data.body
      //   }
      // })
    },
    // 查询
    handleSearch() {
      if (this.searchData.cmhkId === '') {
        this.$message.error('请先选择公司')
      } else {
        this.initData(this.searchData)
      }
    },
    selectDate(val) {
      this.searchData.startDate = val[0]
      this.searchData.endDate = val[1]
    },
    // 重置查询条件
    handleClear() {
      this.searchData = {
        startDate: '',
        endDate: '',
        date: '',
        cmhkId: '',
        page: {
          pageNum: 1,
          pageSize: 10
        }
      }
    },
    selectCompany(val) {
      this.searchData.cmhkId = val
      this.handleSearch()
      if (val === '') {
        this.tableData = []
      }
    },
    handleAddDoc() {
      if (this.searchData.cmhkId === '') {
        this.$message.error('请先选择公司')
      } else {
        this.fileList = []
        this.fileListAdd = []
        this.dialogTableData = []
        this.dialogTableDataAdd = []
        this.dialogVisibleAdd = true
        this.ifDisabled = false
        this.addForm.cmhkId = this.searchData.cmhkId
      }
    },
    // 选取文件
    changeFiles(file, fileList) {
      console.log(file);
      this.dialogTableData = fileList.map(value => {
        return Object.assign({}, value, this.saveId)
      })
      const formFile = new FormData()
      formFile.append('cmhkId', this.saveId.cmhkId)
      formFile.append('archivesId', this.saveId.archivesId)
      formFile.append('file', file.raw)
      formFile.append('name', file.name)
      autoUploadFile(formFile).then(res => {
        if (res.data.code === '0') {
          this.$message.success('上传成功')
        }
      })
    },
    // 新增选取文件
    changeFilesAdd(file, fileList) {
      console.log(file);
      this.fileListAdd = fileList
      this.dialogTableDataAdd = fileList.map(value => {
        return Object.assign({}, value, {isEditing: true})
      })
      getFileType().then(res =>{
        if (res.data.code === '0') {
          this.fileTableColumns[0].selectData = res.data.body
        }
      })
    },
    // 新增移除文件
    removeFile(file, fileList) {
      this.fileListAdd = fileList
      this.dialogTableDataAdd = fileList.map(value => {
        return Object.assign({}, value, {isEditing: true})
      })
    },
    delRow(row) {
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          archivesId: row.archivesId,
          cmhkId: row.cmhkId,
          name: row.name
        }
        deleteArchivesFile(data).then(res => {
          if (res.data.code === '0') {
            this.$message.success('删除成功')
            queryOneArchives(this.saveId).then(res => {
              if (res.data.code === '0') {
                this.addForm = res.data.body
                this.fileList = res.data.body.list
                this.dialogTableData = res.data.body.list
              }
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 下载文件
    downLoadFile(row) {
      window.open(row.fileUrl)
    },
    // 修改文件信息
    editFiles(row) {
      console.log(row)
      this.dialogFiles = true
      getFileType().then(res => {
        this.documentTypeOption = res.data.body
      })
      const data = { parentId: row.documentType }
      getDetailFileType(data).then(res => {
        this.documentCategoryOption = res.data.body
        queryFileInfor(row).then(res => {
          this.fileForm = res.data.body
        })
      })
    },
    // 文件大类指变化时
    changeType(val) {
      const data = {
        parentId: val
      }
      getDetailFileType(data).then(res => {
        this.documentCategoryOption = res.data.body
        this.fileForm.documentCategory = ''
      })
    },
    // 取消文件修改
    handleCancleFile() {
      this.resetForm('file')
      this.dialogFiles = false
    },
    // 点击确定修改文件
    handleSubmitFile(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          editFileInfor(this.fileForm).then(res => {
            if (res.data.code === '0') {
              this.dialogFiles = false
              queryOneArchives(this.saveId).then(res => {
                if (res.data.code === '0') {
                  this.addForm = res.data.body
                  this.fileList = res.data.body.list
                  this.dialogTableData = res.data.body.list
                }
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 选择文件类型大类的选择器事件
    handleSelect(val) {
      const data = {
        parentId: val
      }
      getDetailFileType(data).then(res => {
        if (res.data.code === '0') {
          this.fileTableColumns[1].selectData = []
          this.fileTableColumns[1].selectData = res.data.body
        }
      })
    },
    // 点击确定新增
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = {
            ...this.addForm
          }
          const formFile = new FormData()
          this.fileListAdd.forEach(item => {
            formFile.append('files', item.raw)
          })
          formFile.append('cmhkId', params.cmhkId)
          formFile.append('archivesType', params.archivesType)
          formFile.append('archivesName', params.archivesName)
          formFile.append('archivesDate', params.archivesDate)
          formFile.append('explanation', params.explanation)
          formFile.append('list', JSON.stringify(this.dialogTableDataAdd))
          addArchives(formFile).then(res => {
            if (res.data.code === '0') {
              this.resetForm('form')
              this.dialogVisibleAdd = false
              this.$message.success('新增成功')
              this.initData(this.searchData)
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          return false
        }
      })
    },
    // 点击确认修改
    handleSubmitEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = {
            ...this.addForm,
            list: this.dialogTableData
          }
          updateArchives(data).then(res => {
            if (res.data.code === '0') {
              this.resetForm('form')
              this.dialogVisibleEdit = false
              this.$message.success('修改成功')
              this.initData(this.searchData)
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleCancleAdd() {
      this.resetForm('form')
      this.dialogVisibleAdd = false
    },
    handleCancleEdit() {
      this.resetForm('form')
      this.dialogVisibleEdit = false
    },
    windowWidth(val) {
      if (val < 992) {
        this.$nextTick(() => {
          this.smallSize = false
          this.$refs.ref.style.height = 'calc(100vh - 305px)'
          this.height = this.$refs.ref.offsetHeight
        })
      } else {
        this.$nextTick(() => {
          this.smallSize = true
          this.$refs.ref.style.height = 'calc(100vh - 260px)'
          this.height = this.$refs.ref.offsetHeight
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .app {
    height: 100%;
    .search-bar {
      width: 100%;
      background-color: #ffffff;
      margin-bottom: 10px;
      padding: 10px 0;
    }
    .search-bar-small {
      width: calc(100% - 20px);
      background-color: #ffffff;
      margin-bottom: 10px;
      padding: 10px 10px;
    }
    .table-box {
      width: 100%;
      height: calc(100vh - 260px);
      .but-nav {
        width: calc(100% - 40px);
        padding: 10px 20px;
        background-color: #ffffff;
      }
      .table {
        height: 100%;
      }
    }
    .table-box2 {
      width: 100%;
      height: calc(100vh - 230px);
      .but-nav {
        width: calc(100% - 40px);
        padding: 10px 20px;
        background-color: #ffffff;
      }
      .table {
        height: 100%;
      }
    }
    .select-item {
      width: 100%;
    }
  }
</style>
<style>
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-input.is-disabled .el-input__inner {
    background-color:rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
  .el-textarea.is-disabled .el-textarea__inner {
    background-color: rgb(228,231,237,0.15);
    border-color: #E4E7ED;
    color: #606266;
  }
</style>